package com.innovation.chengzhangriji.ui.task;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.util.FileUtils;
import com.innovation.chengzhangriji.util.Size;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReadImageSizeTask extends AsyncTask<String, Void, Size> {

    public String mUrl;

    private ImageView mImage;

    public ReadImageSizeTask(ImageView imageView) {
        this.mImage = imageView;
    }

    @Override
    protected Size doInBackground(String... params) {
        Size size = new Size(0, 0);
        try {
            mUrl = params[0];
            URL url = new URL(mUrl);
            System.out.println("url:" + mUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=0-255");
            InputStream stream = connection.getInputStream();
            byte[] buffer = new byte[256];
            stream.read(buffer);
            connection.disconnect();
            // BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
            // size = new Size(options.outWidth, options.outHeight);
            // 分析文件格式
            size = FileUtils.decodeImageSize(buffer);
            System.out.println("size:"+ size.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return size;
    }

    @Override
    protected void onPostExecute(Size size) {
        super.onPostExecute(size);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mImage.getLayoutParams();
        params.width = size.getWidth();
        params.height = size.getHeight();
        mImage.setLayoutParams(params);
    }
}
